import * as service from '../services';
import router from 'umi/router';

export default {
  namespace: 'block',
  state: {
    data: {
      miner: {},
    },
  },
  reducers: {
    save(state, { payload: { data }}) {
      return { ...state, data };
    }
  },
  effects: {
    *fetch({ payload: { hashOrHeight }}, {call, put}) {
      const result = yield call(service.getBlock, hashOrHeight);
      if (!result.data) {
        router.push('/404');
        return
      }
      yield put({
        type: 'save',
        payload: {
          data: result.data,
        }
      })
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname.startsWith('/block/')) {
          let paths = location.pathname.split('/');
          let hashOrHeight = paths.pop();
          dispatch({ type: 'fetch', payload: { hashOrHeight } });
        }
      });
    },
  },
}
